﻿using System.ComponentModel.DataAnnotations;
using Ding.HttpHelper;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using SelfService.HaiTai.Models;
using SelfService.HaiTai.Models.Appointment;
using SelfService.Model.Interface;
using SelfService.Model.Models;
using TT;
using WalkingTec.Mvvm.Core;

namespace SelfService.HaiTai
{
    public class HaiTaiAppointment : IAppointment
    {
        private readonly WTMContext _wtm;
        private readonly string _url;

        public HaiTaiAppointment(IOptions<AppSettings> options, WTMContext wtm)
        {
            _wtm = wtm;
            this._url = options.Value.AppointmentUrl;
            #if DEBUG
            this._url = "http://192.168.0.238:8081";
#endif
        }

        /// <summary>
        /// 查询科室信息
        /// </summary>
        /// <param name="body"></param>
        /// <returns></returns>
        public async Task<ResultDetail<object>> GetDepartmentInfo(string body)
        {
            var request = new DepartmentInfoRequest();
            request.HospitalId = "100369001";
            request.DeptId = "";
            request.DepType = "";
            var xml = request.ToXml();
            HttpResult response = default;
            try
            {
                var item = new HttpItem();
                item.URL = $"{_url}/doReqToHis?user=admin&password=123456&service=appointment.getDeptInfo";
                item.ContentType = "application/xml;charset=utf-8";
                item.Postdata = xml;
                item.Method = "POST";
                await Task.Run(() =>
                {
                    response = new HttpHelper().GetHtml(item);
                });

                if (response != null && response.Html.XmlTryParseToObject(out DepartmentInfoResponse result))
                {
                    if (result.ResultCode == "0")
                    {
                        return new ResultDetail<object>()
                        {
                            Data = result.DeptInfo
                        };
                    }
                    return new ResultDetail<object>()
                    {
                        Code = 1,
                        Message = result.ResultDesc,
                        Request = xml,
                        Response = response.Html
                    };
                }
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = "获取科室列表失败",
                    Request = xml,
                    Response = response?.Html
                };
            }
            catch (Exception e)
            {
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = $"获取科室列表异常:{JsonConvert.SerializeObject(e)}",
                    Request = xml,
                    Response = response?.Html
                };
            }
        }

        /// <summary>
        /// 查询医生信息
        /// </summary>
        /// <param name="body"></param>
        /// <returns></returns>
        public async Task<ResultDetail<object>> GetDoctorInfo(string body)
        {
            if (!body.TryJsonParse(out DoctorInfoRequest request))
            {
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = "查询医生列表失败, 解析请求数据异常",
                    Request = body
                };
            }

            if (request.DeptId.IsNullOrWhiteSpace())
            {
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = "查询医生列表失败, 科室ID不能为空",
                    Request = body
                };
            }
            if (request.HospitalId.IsNullOrWhiteSpace()) request.HospitalId = "100369001";
            if (request.StartDate.IsNullOrWhiteSpace()) request.StartDate = DateTime.Now.ToString("yyyy-MM-dd");
            if (request.EndDate.IsNullOrWhiteSpace()) request.EndDate = DateTime.Now.ToString("yyyy-MM-dd");
            var xml = request.ToXml();
            HttpResult response = default;
            try
            {
                var item = new HttpItem();
                item.URL = $"{_url}/doReqToHis?user=admin&password=123456&service=appointment.getScheduleInfo";
                item.ContentType = "application/xml;charset=utf-8";
                item.Postdata = xml;
                item.Method = "POST";
                await Task.Run(() =>
                {
                    response = new HttpHelper().GetHtml(item);
                });
                if (response != null && response.Html.XmlTryParseToObject(out DoctorInfoResponse result))
                {
                    if (result.ResultCode == "0")
                    {
                        return new ResultDetail<object>()
                        {
                            Data = result.RegInfo
                        };
                    }
                    return new ResultDetail<object>()
                    {
                        Code = 1,
                        Message = result.ResultDesc,
                        Request = xml,
                        Response = response.Html
                    };
                }
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = "获取医生列表失败",
                    Request = xml,
                    Response = response?.Html
                };
            }
            catch (Exception e)
            {
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = $"获取医生列表异常:{JsonConvert.SerializeObject(e)}",
                    Request = xml,
                    Response = response?.Html
                };
            }
        }

        /**
         * 查询坐班时段
         */
        public async Task<ResultDetail<object>> GetTimeInfo(string body)
        {
            if (!body.TryJsonParse(out TimeInfoRequest request))
            {
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = "查询医生坐班时段失败, 解析请求数据异常",
                    Request = body
                };
            }

            if (request.DeptId.IsNullOrWhiteSpace())
            {
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = "查询医生坐班时段失败, 科室ID不能为空",
                    Request = body
                };
            }
            if (request.HospitalId.IsNullOrWhiteSpace()) request.HospitalId = "100369001";
            var xml = request.ToXml();
            HttpResult response = default;
            try
            {
                var item = new HttpItem();
                item.URL = $"{_url}/doReqToHis?user=admin&password=123456&service=appointment.getTimeInfo";
                item.ContentType = "application/xml;charset=utf-8";
                item.Postdata = xml;
                item.Method = "POST";
                await Task.Run(() =>
                {
                    response = new HttpHelper().GetHtml(item);
                });
                if (response != null && response.Html.XmlTryParseToObject(out TimeInfoResponse result))
                {
                    if (result.ResultCode == "0")
                    {
                        return new ResultDetail<object>()
                        {
                            Data = result.TimeRegInfo
                        };
                    }
                    return new ResultDetail<object>()
                    {
                        Code = 1,
                        Message = result.ResultDesc,
                        Request = xml,
                        Response = response.Html
                    };
                }
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = "查询医生坐班时段失败",
                    Request = xml,
                    Response = response?.Html
                };
            }
            catch (Exception e)
            {
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = $"查询医生坐班时段异常:{JsonConvert.SerializeObject(e)}",
                    Request = xml,
                    Response = response?.Html
                };
            }
        }

        public async Task<ResultDetail<object>> GetRegFee(string body)
        {
            if (!body.TryJsonParse(out GetRegFeeRequest request))
            {
                return new ResultDetail<object>
                {
                    Code = 1,
                    Message = "查询挂号费用失败, 解析请求数据异常",
                    Request = body
                };
            }
            if (request.HospitalId.IsNullOrWhiteSpace()) request.HospitalId = "100369001";
            var context = new ValidationContext(request);
            var results = new List<ValidationResult>();
            if (!Validator.TryValidateObject(request, context, results, true))
            {
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = $"查询挂号费用失败. {string.Join('|', results.Select(e => e.ErrorMessage))}",
                    Request = body
                };
            }
            if (request.HospitalId.IsNullOrWhiteSpace()) request.HospitalId = "100369001";
            var xml = request.ToXml();
            HttpResult response = default;
            try
            {
                var item = new HttpItem();
                item.URL = $"{_url}/doReqToHis?user=admin&password=123456&service=support.getRegFee";
                item.ContentType = "application/xml;charset=utf-8";
                item.Postdata = xml;
                item.Method = "POST";
                await Task.Run(() =>
                {
                    response = new HttpHelper().GetHtml(item);
                });
                if (response != null && response.Html.XmlTryParseToObject(out GetRegFeeResponse result))
                {
                    if (result.ResultCode == "0")
                    {
                        return new ResultDetail<object>()
                        {
                            Data = result
                        };
                    }
                    return new ResultDetail<object>()
                    {
                        Code = 1,
                        Message = result.ResultDesc,
                        Request = xml,
                        Response = response.Html
                    };
                }
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = "查询挂号费用失败",
                    Request = xml,
                    Response = response?.Html
                };
            }
            catch (Exception e)
            {
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = $"查询挂号费用异常:{JsonConvert.SerializeObject(e)}",
                    Request = xml,
                    Response = response?.Html
                };
            }
        }

        /// <summary>
        /// 现场挂号
        /// </summary>
        /// <param name="body"></param>
        /// <returns></returns>
        public async Task<ResultDetail<object>> AddOrder(string body)
        {
            if (!body.TryJsonParse(out AddOrderRequest request))
            {
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = "当日挂号失败, 解析请求数据异常",
                    Request = body
                };
            }

            var context = new ValidationContext(request);
            var results = new List<ValidationResult>();
            if (!Validator.TryValidateObject(request, context, results, true))
            {
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = $"当日挂号失败. {string.Join('|', results.Select(e => e.ErrorMessage))}",
                    Request = body
                };
            }
            if (request.HospitalId.IsNullOrWhiteSpace()) request.HospitalId = "100369001";
            var xml = request.ToXml();
            HttpResult response = default;
            try
            {
                var item = new HttpItem();
                item.URL = $"{_url}/doReqToHis?user=admin&password=123456&service=appointment.addOrder";
                item.ContentType = "application/xml;charset=utf-8";
                item.Postdata = xml;
                item.Method = "POST";
                await Task.Run(() =>
                {
                    response = new HttpHelper().GetHtml(item);
                });
                if (response != null && response.Html.XmlTryParseToObject(out AddOrderResponse result))
                {
                    if (result.ResultCode == "0")
                    {
                        return new ResultDetail<object>()
                        {
                            Data = result
                        };
                    }
                    return new ResultDetail<object>()
                    {
                        Code = 1,
                        Message = result.ResultDesc,
                        Request = xml,
                        Response = response.Html
                    };
                }
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = "当日挂号列表失败",
                    Request = xml,
                    Response = response?.Html
                };
            }
            catch (Exception e)
            {
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = $"当日挂号异常:{JsonConvert.SerializeObject(e)}",
                    Request = xml,
                    Response = response?.Html
                };
            }
        }

        /// <summary>
        /// 支付
        /// </summary>
        /// <param name="body"></param>
        /// <returns></returns>
        public async Task<ResultDetail<object>> Pay(string body)
        {
            if (!body.TryJsonParse(out OrderPayRequest request))
            {
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = "预约挂号失败, 解析请求数据异常",
                    Request = body
                };
            }
            request.OperatorId = _wtm.LoginUserInfo.ITCode;
            var context = new ValidationContext(request);
            var results = new List<ValidationResult>();
            if (request.HospitalId.IsNullOrWhiteSpace()) request.HospitalId = "100369001";
            if (!Validator.TryValidateObject(request, context, results, true))
            {
                return new ResultDetail<object>
                {
                    Code = 1,
                    Message = $"预约挂号失败. {string.Join('|', results.Select(e => e.ErrorMessage))}",
                    Request = body
                };
            }
            var xml = request.ToXml();
            HttpResult response = default;
            try
            {
                var item = new HttpItem();
                item.URL = $"{_url}/doReqToHis?user=admin&password=123456&service=appointment.pay";
                item.ContentType = "application/xml;charset=utf-8";
                item.Postdata = xml;
                item.Method = "POST";
                await Task.Run(() =>
                {
                    response = new HttpHelper().GetHtml(item);
                });
                if (response != null && response.Html.XmlTryParseToObject(out OrderPayResponse result))
                {
                    if (result.ResultCode == "0")
                    {
                        return new ResultDetail<object>()
                        {
                            Data = result
                        };
                    }
                    return new ResultDetail<object>()
                    {
                        Code = 1,
                        Message = result.ResultDesc,
                        Request = xml,
                        Response = response.Html
                    };
                }
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = "预约挂号失败列表失败",
                    Request = xml,
                    Response = response?.Html
                };
            }
            catch (Exception e)
            {
                return new ResultDetail<object>()
                {
                    Code = 1,
                    Message = $"预约挂号失败异常:{JsonConvert.SerializeObject(e)}",
                    Request = xml,
                    Response = response?.Html
                };
            }
        }
    }
}
